package com.wendu.oa.service.security.impl;

import com.wendu.oa.common.page.PageUtils;
import com.wendu.oa.dao.security.RoleDao;
import com.wendu.oa.dto.MenuDto;
import com.wendu.oa.dto.RoleDto;
import com.wendu.oa.model.Fun;
import com.wendu.oa.service.security.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleDao roleDao;

    @Override
    public Map<String, Object> getRolePage(RoleDto roleDto) {
        return PageUtils.getPage(roleDto,()-> roleDao.findRoleList(roleDto));
    }

    @Override
    public void setFuns(Integer ro_id, Integer[] f_ids) {

        roleDao.deleteRoleAllFuns(ro_id);

        if(f_ids == null || f_ids.length == 0)return;

        roleDao.insertRoleFuns(ro_id,f_ids);
    }

    @Override
    public List<MenuDto> getFunList() {
        List<MenuDto> mainList = new ArrayList<>();

        List<Fun> funList = roleDao.findFunList();

        MenuDto current = null;//当前主菜单

        for(Fun fun : funList){
            if(current == null || !current.getMenuId().equals(fun.getP_id())){
                current = new MenuDto();
                mainList.add(current);
                current.setMenuId(fun.getP_id());
                current.setMenuName(fun.getP_name());
                current.setChildren(new ArrayList<MenuDto>());
            }
            MenuDto sub = new MenuDto();
            sub.setMenuId(fun.getC_id());
            sub.setMenuName(fun.getC_name());
            sub.setMenuUrl(fun.getUrl());
            current.getChildren().add(sub);

        }

        return mainList;

    }

    @Override
    public Integer[] getRoleFunIds(Integer ro_id) {
        return roleDao.findRoleFunIds(ro_id);
    }
}
